﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace TiaoTiaoCode.MultiLanguage
{
    /// <summary>
    /// 多语言支持
    /// </summary>
    public class TiaoTiaoMultiLang
    {
        /// <summary>
        /// 系统当前可支持动态切换的语言列表
        /// </summary>
        public static readonly Dictionary<string, string> _supportDic = new()
        {
            ["中文"] = "zh-CHS",
            ["English"] = "en-US",
            ["Deutsch"] = "de"
        };

        #region 属性

        /// <summary>
        /// 是否启用多语言
        /// </summary>
        public static bool InUseMultiLang { get; private set; } = false;

        /// <summary>
        /// 多语言根目录
        /// </summary>
        public static string LangRootPath { get; private set; }

        /// <summary>
        /// 当前语言
        /// </summary>
        public static string CurLangKey { get; private set; }

        /// <summary>
        /// 返回系统支持的语言列表
        /// </summary>
        public static List<string> SupportLangs => _supportDic.Keys.ToList();

        /// <summary>
        /// 获取当前可用语言列表
        /// </summary>
        public static List<string> CanUseLangs
        {
            get
            {
                if (!Directory.Exists(LangRootPath)) return default!;

                // 语言包文件夹下的对应语言包目录
                var langDirInfos = new DirectoryInfo(LangRootPath).GetDirectories();
                var langDirs = langDirInfos.Select(t => t.Name).ToArray();

                // 与当前支持的语言做交集，就是当前实际可支持的语言
                var values = _supportDic.Values.Intersect(langDirs).ToList();

                return _supportDic.Where(t => values.Contains(t.Value)).Select(t => t.Key).ToList();
            }
        }

        /// <summary>
        /// 当前语言的对应转换字典
        /// </summary>
        public static Dictionary<string, string> CurLangDictionary { get; private set; } = default!;

        #endregion

        #region 公开方法

        /// <summary>
        /// 添加支持语言
        /// 在项目启动时，使用该方法增加支持语言
        /// </summary>
        /// <param name="langName">语言选择项名称</param>
        /// <param name="cultureInfoName">CultureInfo 名，也是对应语言文件夹名</param>
        public static void AddSupportLang(string langName, string cultureInfoName)
        {
            if (_supportDic.Keys.Contains(langName)) throw new Exception("已有语言包配置");

            _supportDic.Add(langName, cultureInfoName);
        }

        /// <summary>
        /// 应用多语言
        /// </summary>
        public static void UseMultiLang(string rootPath = "")
        {
            if (string.IsNullOrWhiteSpace(rootPath))
                LangRootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lang");
            else
                LangRootPath = rootPath;

            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-CHS");

            InUseMultiLang = true;
        }

        /// <summary>
        /// 设置语言
        /// </summary>
        /// <param name="langKey">支持的语言列表Key</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static void SetLang(string langKey = "")
        {
            if (!InUseMultiLang) throw new Exception("Multi Language are not Enable. Use the UseMultiLang Method to Open Multi Language.");

            if (string.IsNullOrWhiteSpace(langKey)) return;

            if (!_supportDic.ContainsKey(langKey)) throw new Exception("Not Supported Lang Key");

            CurLangKey = langKey;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(_supportDic[langKey]);

            var path = Path.Combine(LangRootPath, _supportDic[langKey]);
            if (Directory.GetFiles(path).Length <= 0) throw new Exception("Not exist Files");

            CurLangDictionary = JsonLangHelper.LoadJsonLang(path);
        }

        /// <summary>
        /// 转换Xaml资源语言文件为json语言文件
        /// </summary>
        /// <param name="langXamlFilePath">资源文件完整路径</param>
        /// <param name="saveJsonLangFilePath">保存文件的完整路径</param>
        public static void ChangeAndSaveFile(string langXamlFilePath, string saveJsonLangFilePath)
        {
            var reg = new Regex(".*\"(?<key>.*)\">(?<value>.*)<");
            var originLang = File.ReadAllText(langXamlFilePath);

            var lines = originLang.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            var dic = new Dictionary<string, string>();
            foreach (var line in lines)
            {
                var match = reg.Match(line);
                if (match.Success)
                {
                    var key = match.Groups["key"].Value;
                    var value = match.Groups["value"].Value;

                    if (dic.ContainsKey(key))
                        dic[key] = value;
                    else
                        dic.Add(key, value);
                }
            }

            var str = JsonConvert.SerializeObject(dic, Formatting.Indented);

            File.WriteAllText(saveJsonLangFilePath!, str);
        }

        #endregion
    }
}
